package com.flyfinger.conf;

import com.zaxxer.hikari.HikariDataSource;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author zhouyp
 * @program auto-pull-conf
 * @description
 * @create 2020-06-24
 */
public class DataSourceConfig {

	private DataSourceConfig() {
	}

	private static Connection connection;
	private static volatile boolean LOCK = false;

	public static Connection getConnection() {
		while (LOCK) {

		}
		if (connection == null) {
			try {
				setConnection();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				LOCK = false;
			}
		}
		return connection;
	}

	public static void setConnection() throws IOException, SQLException {
		final Properties jdbcConfig = getJDBCConfig();
		final HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		dataSource.setJdbcUrl(jdbcConfig.get("url").toString());
		dataSource.setUsername(jdbcConfig.get("username").toString());
		dataSource.setPassword(jdbcConfig.get("password").toString());
		connection = dataSource.getConnection();
		LOCK = false;
	}

	public static void main(String[] args) throws IOException {
		getJDBCConfig();
	}

	private static Properties getJDBCConfig() throws IOException {
		LOCK = true;
		final String path = System.getProperty("user.dir") +
				File.separator +
				"jdbc.properties";
		final Properties properties = new Properties();

		properties.load(new FileInputStream(path));
		return properties;
	}
}
